package ext.acae2.document.commands;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import wt.doc.WTDocument;
import wt.fc.QueryResult;
import wt.fc.ReferenceFactory;
import wt.fc.collections.WTHashSet;
import wt.fc.collections.WTKeyedMap;
import wt.folder.Folder;
import wt.folder.FolderHelper;
import wt.inf.container.WTContainer;
import wt.inf.container.WTContainerRef;
import wt.log4j.LogR;
import wt.org.WTUser;
import wt.pom.Transaction;
import wt.session.SessionHelper;
import wt.session.SessionServerHelper;
import wt.util.WTException;
import wt.util.WTProperties;
import ext.acae2.document.bean.ProgramPackBean;
import ext.acae2.document.helper.ProgramPackHelper;
import ext.acae2.util.FileUtil;
import ext.acae2.util.QueryUtil;

/**
 * @desription 工程文件包创建处理
 * @author cnie
 * @date 2013-8-6 下午7:01:52
 */
public class ProgramPackCommands {
	
	private final static Logger LOGGER = LogR
			.getLogger(ProgramPackCommands.class.getName());

	private static String tempFolder;

	static {
		try {
			tempFolder = WTProperties.getLocalProperties().getProperty(
					"wt.temp");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 
	 * @description 工程文件包处理入口
	 * @author cnie
	 * @date 2013-8-6 下午6:47:22
	 * @version 1.0
	 * @param request
	 * @return
	 * @throws WTException 
	 * @throws Exception
	 */
	public static String execute(HttpServletRequest request) throws WTException{
		
		StringBuffer errorSb = new StringBuffer("");
		
		Transaction trans =null;
		boolean enforced = SessionServerHelper.manager.setAccessEnforced(false);
		
		WTUser user = (WTUser) SessionHelper.manager.getPrincipal();
		
		long currentTime = System.currentTimeMillis();
		
		String programTempFolderStr = user.getName()+currentTime;
		
		File programtempFolder = new File(tempFolder+File.separator+programTempFolderStr);//临时存储根目录
		try{
			
			if(!programtempFolder.exists())
				programtempFolder.mkdirs();
			
			String xlsFilePath = ProgramPackHelper.parseUploadFile(request, programtempFolder);
			
			if(xlsFilePath==null){
				errorSb.append("上传的工程文件不存在Excel文件,<font style=\"color:red\">处理失败</font>");
				return errorSb.toString();
			}
			String programUnzipFolderStr = xlsFilePath.substring(0,xlsFilePath.lastIndexOf(File.separator));
			
			LOGGER.info("programUnzipFolderStr>>>>>>>>>>"+programUnzipFolderStr);
			
			LOGGER.info("read xls begin");
			List<ProgramPackBean> programPackBeans = ProgramPackHelper.readExcel(xlsFilePath,errorSb);
			LOGGER.info("programPackBeans size()>>>>>>>>>"+programPackBeans.size());
			LOGGER.info("read xls end");
			
			if(StringUtils.isNotBlank(errorSb.toString())&&errorSb.indexOf("处理失败")>-1){
				return errorSb.toString();
			}
			
			WTContainer container = QueryUtil.getContainerByName(ProgramPackHelper.LIB_NAME);
//			String folderName = "/Default/"+programPackBeans.get(0).getSendDept().trim()+"/"+ProgramPackHelper.SUB_FOLDER_NAME;
			ReferenceFactory rf = new ReferenceFactory();
			WTContainerRef containerRef = (WTContainerRef) rf.getReference(container);
			
//			Folder folderA=FolderHelper.service.getFolder(folderName+"/"+ProgramPackHelper.A_FOLDER_NAME, containerRef);
//			Folder folderB=FolderHelper.service.getFolder(folderName+"/"+ProgramPackHelper.B_FOLDER_NAME, containerRef);
//			WTHashSet wtSet = new WTHashSet();
//			wtSet.add(folderA);
//			wtSet.add(folderB);
//			QueryResult exitDocQr = FolderHelper.service.findFolderContents(folderA);
//			exitDocQr.append(FolderHelper.service.findFolderContents(folderB).getObjectVectorIfc());
			
			QueryResult exitDocQr  = new QueryResult();
			
			trans = new Transaction();
			trans.start();
			
			for(ProgramPackBean programPackBean:programPackBeans){
				File secondFile = null;
				if(StringUtils.isNotBlank(programPackBean.getFilePackName())){
					String secondFileStr = programUnzipFolderStr+File.separator+programPackBean.getFilePackName();
					secondFile = new File(secondFileStr);
				}
				ProgramPackHelper.createProgramDoc(programPackBean, secondFile,errorSb,exitDocQr,containerRef);
			}
			trans.commit();
		}catch(Exception e){
			trans.rollback();
			e.printStackTrace();
			errorSb=new StringBuffer("");
			errorSb.append("<font style=\"color:red\">处理失败，系统出现异常</font>");
		}finally{
			if(trans!=null)
				trans=null;
			SessionServerHelper.manager.setAccessEnforced(enforced);
			if(programtempFolder!=null)
				FileUtil.deleteDir(programtempFolder);
		}
		return errorSb.toString();
	}

}
